<template>
  <div class="transfer-add-container">
    <!-- 门仓选择区域 -->
    <el-form :inline="true" class="store-select-form" style="display: flex; justify-content: space-between">
      <div>
        <template v-if="defaultTransferOutType == 0">
          <el-form-item label="供应商:">
            <el-select v-model="merId" placeholder="请选择供应商" @change="handleSupplierChange">
              <el-option v-for="item in supplierList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </template>
        <template v-if="defaultTransferOutType == 1">
          <el-form-item label="调出门仓:">
            <el-cascader
              v-model="transferOutStoreId"
              :options="storeList"
              :props="{ expandTrigger: 'hover', value: 'id', label: 'name' }"
              @change="handleTransferOutStoreChange"
            ></el-cascader>
          </el-form-item>
        </template>
        <template v-if="defaultTransferInType == 3">
          <el-form-item :label="sendType == '采购入库' ? '入库仓库:' : '出库仓库:'">
            <el-select v-model="warehouseId" placeholder="请选择入库仓库" @change="handleWarehouseChange">
              <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </template>
        <template v-if="defaultTransferInType == 1">
          <el-form-item label="调入门仓:">
            <el-cascader
              ref="transferInStore"
              v-model="transferInStoreId"
              :options="storeList"
              :props="{ expandTrigger: 'hover', value: 'id', label: 'name' }"
              @change="handleTransferInStoreChange"
            ></el-cascader>
          </el-form-item>
        </template>

        <!-- {{transferTableDataWithAdd}} -->
        <el-form-item label="单据时间:" prop="receiptTime" v-if="defaultTransferOutType == 0">
          <!-- <el-input v-model="receiptTime" placeholder="请选择单据时间" /> -->
          <el-date-picker v-model="receiptTime" type="date" placeholder="选择日期" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="备注说明:">
          <el-input v-model="remarks" placeholder="请输入备注说明" />
        </el-form-item>
        <el-form-item label="调拨类型:" v-if="defaultTransferOutType == 1 && transferType != ''">
          <!-- <el-input  :value="distributeType(transferType)"   />
          {} -->
          <span style="width: 100px; text-align: center">
            {{ distributeType(transferType) }}
          </span>
        </el-form-item>
      </div>
      <div>
        <el-form-item>
          <el-button type="primary" @click="submitted" :disabled="transferTableDataWithAdd.length == 0"
            >提交审核</el-button
          >
        </el-form-item>
      </div>
    </el-form>
    <!-- 调拨单表格 -->
    <div class="transfer-table-wrapper">
      <div style="display: flex; justify-content: flex-start; margin-bottom: 10px">
        <el-button type="primary"  @click="handlePrev">返回</el-button>
        <el-button type="primary" @click="addProduct" :disabled="isAddProductDisabled">添加商品</el-button>
      </div>
      <el-table :data="transferTableDataWithAdd" border stripe size="small">
        <el-table-column prop="index" label="序号" width="60" align="center">
          <template slot-scope="scope">
            <span v-if="!scope.row.isAdd">{{ (scope.$index + 1) | padIndex }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="商品名称" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.productName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="barCode" label="商品编码" align="center"> </el-table-column>
        <el-table-column prop="image" label="图片" align="center" width="70">
          <template slot-scope="scope">
            <img
              v-if="!scope.row.isAdd"
              :src="scope.row.image"
              alt=""
              style="width: 40px; height: 40px; object-fit: cover; border-radius: 4px; border: 1px solid #eee"
            />
          </template>
        </el-table-column>
        <el-table-column prop="sku" label="商品规格" align="center">
          <template slot-scope="scope">
            <span v-if="!scope.row.isAdd">{{ scope.row.sku }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="productAttrValueId" label="商品编码" align="center">
          <template slot-scope="scope">
            <span v-if="!scope.row.isAdd">{{ scope.row.productAttrValueId }}</span>
          </template>
        </el-table-column> -->
        <el-table-column prop="unitName" label="单位" align="center" width="60">
          <template slot-scope="scope">
            <span v-if="!scope.row.isAdd">{{ scope.row.unitName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="单价" align="center">
          <template slot-scope="scope">
            <span v-if="!scope.row.isAdd">{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="returnStock" label="仓库库存" align="center" v-if="sendType == '退货出库'">
          <!-- <template slot-scope="scope">
            <span v-if="!scope.row.isAdd">{{ scope.row.transferOutStoreThereturnStocknStock }}</span>
          </template> -->
        </el-table-column>
        <el-table-column
          prop="transferOutStoreThenStock"
          label="调出门仓库存"
          align="center"
          v-if="defaultTransferOutType == 1"
        >
          <template slot-scope="scope">
            <span v-if="!scope.row.isAdd">{{ scope.row.transferOutStoreThenStock }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="number" label="数量" align="center">
          <template slot-scope="scope">
            <el-input-number
              v-if="!scope.row.isAdd"
              v-model="scope.row.number"
              :min="1"
              :max="defaultTransferOutType == 1 ? scope.row.transferOutStoreThenStock : 99999"
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column prop="number" label="金额" align="center" v-if="defaultTransferOutType == 0">
          <template slot-scope="scope">
            <span v-if="scope.row.number">{{ scope.row.number * scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="transferInStoreThenStock"
          label="调入门仓库存"
          align="center"
          v-if="defaultTransferOutType == 1"
        >
          <template slot-scope="scope">
            <span v-if="!scope.row.isAdd">{{ scope.row.transferInStoreThenStock || 0 }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="remark" label="备注" align="center">
          <template slot-scope="scope">
            <el-input v-if="!scope.row.isAdd" v-model="scope.row.remark" size="small" placeholder="请输入备注" />
          </template>
        </el-table-column> -->
        <el-table-column label="操作" align="center" width="100">
          <template slot-scope="scope">
            <div v-if="!scope.row.isAdd" style="display: flex; justify-content: center; align-items: center">
              <!-- <el-button type="text" size="small" @click="handleRowAdd(scope.$index)">+</el-button> -->
              <el-button type="text" size="small" @click="handleRowRemove(scope.$index)" style="color: red"
                >移除</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-drawer
      title="请选择商品"
      :visible.sync="showDrawer"
      size="60%"
      direction="rtl"
      :before-close="handleDrawerClose"
      custom-class="product-drawer"
    >
      <div class="drawer-content-flex">
        <!-- 分类树结构 -->
        <div class="category-tree-panel">
          <el-tree
            :data="categoryTree"
            :props="treeProps"
            node-key="id"
            highlight-current
            @node-click="handleCategoryClick"
            default-expand-all
          />
        </div>
        <!-- 商品列表区域 -->
        <div class="product-list-panel">
          <div class="product-list-header">
            <el-input
              v-model="searchKeyword"
              placeholder="请输入商品名称"
              style="width: 220px; margin-right: 10px"
              @keyup.enter.native="fetchProductList"
              clearable
            />

             <el-input
              v-model="itemNumber"
              placeholder="商品条码"
              style="width: 220px; margin-right: 10px"
              clearable
              @keyup.enter.native="fetchProductList"

            />
              <el-input
              v-model="barCode"
              placeholder="商品编码"
              style="width: 220px; margin-right: 10px"
              @keyup.enter.native="fetchProductList"
              clearable
            />
            <el-button @click="fetchProductList" size="small" type="primary">搜索</el-button>
          </div>
          <el-table
            :data="productList"
            @selection-change="handleSelectionChange"
            style="width: 100%; margin-top: 10px"
            ref="productTable"
            border
            size="small"
            :row-key="getRowKey"
          >
            <el-table-column type="selection" width="50" align="center" :reserve-selection="true" />
            <el-table-column prop="productName" label="商品名称" align="center" />
            <el-table-column prop="image" label="图片" align="center" width="70">
              <template slot-scope="scope">
                <img
                  :src="scope.row.image"
                  alt=""
                  style="width: 40px; height: 40px; object-fit: cover; border-radius: 4px; border: 1px solid #eee"
                />
              </template>
            </el-table-column>
            <el-table-column prop="sku" label="商品规格" align="center" />
            <el-table-column prop="itemNumber" label="商品条码" align="center" />
            <el-table-column prop="barCode" label="商品编码" align="center" />
            <el-table-column prop="price" label="单价" align="center" />
            <!-- <el-table-column prop="transferOutStoreThenStock" label="库存" align="center" /> -->
          </el-table>
          <el-pagination
            :current-page="page"
            :page-size="pageSize"
            :total="total"
            @current-change="handlePageChange"
            layout="total, prev, pager, next"
            style="margin-top: 10px; text-align: right"
          />
          <div class="drawer-footer-btns">
            <el-button @click="handleDrawerClose">取消</el-button>
            <el-button type="primary" @click="handleBatchAdd">批量添加</el-button>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { productCategoryListApi } from '@/api/product';
import {
  listStore,
  listProductSpec,
  transferOrderSave,
  inventoryTransferSave,
  transferOrderInfo,
  selectPurchaseProductAttrValueList,
  purchaseInWarehouseFormSave,
  addInOrOutWarehouseOrders
} from '@/api/commercial';
import { merchantListApi } from '@/api/merchant';
import { buildProductQueryParams, fetchProducts, checkProductStock, findExistingProduct } from '@/utils/productUtils';
import { BarcodeScanner } from '@/utils/scannerUtils';

export default {
  props: {
    defaultTransferInType: {
      type: Number,
      default: 1,
    },
    defaultTransferOutType: {
      type: Number,
      default: 1,
    },
    sendType: {
      type: String,
      default: '',
    },
  },

  data() {
    return {
      transferType: '', //1:仓库调拨 2:门仓调拨 3:门店调拨
      showDrawer: false,
      searchKeyword: '',
      itemNumber: '',
      barCode: '',
      productList: [],
      selectedProducts: [],
      page: 1,
      pageSize: 10,
      total: 0,
      transferProducts: [],
      supplierList: [],
      merId: '', //供应商id(门店id)
      merName: '', //供应商名称(门店名称)
      warehouseId: '', //入库仓库id
      warehouseName: '', //入库仓库名称
      // 门仓选择相关
      transferOutStoreId: '',
      transferInType: '', //转入类型(1仓库 2门仓)
      transferOutType: '', //转出类型(1仓库 2门仓)
      transferInStoreId: '',
      transferInRoomWarehouseName: '', //调入门仓名称
      transferOutRoomWarehouseName: '', //调出门仓名称
      storeList: [
        { name: '仓库', id: 1, children: [] },
        { name: '门店', id: 2, children: [] },
      ],
      warehouseList: [],
      storeRoomList: [],
      // 分类树相关
      categoryTree: [
        {
          id: 0,
          label: '全部',
          children: [
            {
              id: 1,
              label: '女装',
              children: [
                { id: 11, label: '上衣' },
                { id: 12, label: '下衣' },
              ],
            },
            {
              id: 2,
              label: '男装',
              children: [
                { id: 21, label: '上衣' },
                { id: 22, label: '下衣' },
              ],
            },
          ],
        },
      ],
      treeProps: {
        children: 'children',
        label: 'label',
      },
      selectedCategoryId: '',
      transferTableData: [],
      remarks: '',
      receiptTime: new Date(), //获取当天时间回显
      IsreadOnly: false,
      // 扫描仪输入相关
      scannerBuffer: '',
      scannerTimeout: null,
      scannerDelay: 100, // 扫描仪输入延迟时间(ms)
      lastKeyTime: 0, // 上次按键时间
      keyPressCount: 0, // 按键次数
      isProcessingScanner: false, // 是否正在处理扫描仪输入
      scannerStartTime: 0, // 扫描开始时间
      scanner: null,
    };
  },
  created() {
    this.getStoreList();
    this.getSupplierList();
  },
  mounted() {
    this.initScanner();
  },
  beforeDestroy() {
    if (this.scanner) {
      this.scanner.destroy();
    }
  },
  methods: {
    getRowKey(row) {
      return row.productAttrValueId;
    },
    //1:仓库调拨 2:门仓调拨 3:门店调拨
    distributeType(transferType) {
      if (transferType == 1) {
        return '仓库调拨';
      } else if (transferType == 2) {
        return '门仓调拨';
      } else if (transferType == 3) {
        return '门店调拨';
      } else {
        return '';
      }
    },
    handleSupplierChange(val) {
      this.merName = this.supplierList.find((item) => item.id === val).name;
    },
    handleWarehouseChange(val) {
      this.warehouseName = this.warehouseList.find((item) => item.id === val).name;
    },
    handlePrev() {
      this.$emit('handleBack');
    },
    getTransferOrderDetail(id) {
      transferOrderInfo({ id: id }).then((res) => {
        console.log(res, 288);
        this.transferTableData = res.list || [];
      });
    },
    initScanner() {
      this.scanner = new BarcodeScanner({
        onScan: this.handleScannedProductCode,
      });
      this.scanner.init();
    },
    async handleScannedProductCode(productCode) {
      // 检查必要条件
      if (this.isAddProductDisabled) {
        if (this.defaultTransferOutType === 1) {
          this.$message.warning('请先选择调出门仓和调入门仓');
        } else if (this.defaultTransferOutType === 0) {
          if (this.defaultTransferInType === 3) {
            this.$message.warning('请先选择供应商和入库仓库');
          } else {
            this.$message.warning('请先选择供应商和入库门仓');
          }
        }
        return;
      }

      try {
        // 构建查询参数
        const queryType = this.defaultTransferOutType === 1 ? 'transfer' : 'purchase'; //transfer:调拨  purchase:采购
        const extraParams =
          this.defaultTransferOutType === 1
            ? {
                transferOutStoreId: this.transferOutStoreId[1],
                transferOutType: this.transferOutType,
                transferInStoreId: this.transferInStoreId[1],
                transferInType: this.transferInType,
              }
            :  this.sendType == '采购入库' ? {
                merId: this.merId,
                merName: this.merName,
              } : {
                merId: this.merId,
                merName: this.merName,
                warehouseId: this.warehouseId,
                warehouseName: this.warehouseName,
              };

        const params = buildProductQueryParams({
          barCode: productCode,
          limit: 1,
          page: 1,
          queryType,
          extraParams,
        });

        // 查询商品
        const { list } = await fetchProducts({ ...params, queryType });

        if (list && list.length > 0) {
          const product = list[0];
          const existingIndex = findExistingProduct(this.transferTableData, product);

          if (existingIndex >= 0) {
            // 商品已存在，增加数量
            const currentItem = this.transferTableData[existingIndex];
            const maxStock = checkProductStock(currentItem, queryType);
            console.log(maxStock, 415);
            if (currentItem.number < maxStock) {
              currentItem.number += 1;
              this.$message.success(`商品 ${product.productName} 数量已增加`);
            } else {
              this.$message.warning(`商品 ${product.productName} 库存不足`);
            }
          } else {
            // 添加新商品
            product.number = 1;
            this.transferTableData.push(product);
            this.$message.success(`商品 ${product.productName} 已添加`);
          }
        } else {
          this.$message.error(`未找到商品编码: ${productCode}`);
        }
      } catch (error) {
        console.error('查询商品失败:', error);
        this.$message.error('查询商品失败');
      }
    },
    handleTransferOutStoreChange(val) {
      this.transferOutType = val[0];
      console.log(this.storeList[val[0]]);
      try{
        this.transferOutRoomWarehouseName = this.storeList.find((item) => item.id == val[0]).children.find((item) => item.id == val[1]).name;
      }catch(error){
        this.transferOutRoomWarehouseName = '';
      }
      console.log(val, 467, this.transferOutRoomWarehouseName,this.storeList);
      this.completedTransferType();
    },
    handleTransferInStoreChange(val) {
      this.transferInType = val[0];
      if (
        this.transferInType == this.transferOutType &&
        JSON.stringify(this.transferInStoreId) == JSON.stringify(this.transferOutStoreId)
      ) {
        this.$message.error('调出门仓和调入门仓不能相同');
        this.transferInStoreId = '';
        this.transferType = '';
        this.$nextTick(() => {
          this.$refs.transferInStore.checkedValue.length = 0;
        });
      } else {
        this.completedTransferType();
        try{
          this.transferInRoomWarehouseName = this.storeList.find((item) => item.id == val[0]).children.find((item) => item.id == val[1]).name;
        }catch(error){
          this.transferInRoomWarehouseName = '';
        }
        console.log(val, 467, this.transferInRoomWarehouseName);
      }
    },
    completedTransferType() {
      //1:仓库调拨 仓库 《-》仓库 2:门仓调拨 仓库 《-》门仓 3:门店调拨 门店《-》门店
      if (this.transferOutType == 1 && this.transferInType == 1) {
        this.transferType = 1;
      } else if (this.transferOutType == 2 && this.transferInType == 2) {
        this.transferType = 3;
      } else if (
        (this.transferOutType == 2 && this.transferInType == 1) ||
        (this.transferOutType == 1 && this.transferInType == 2)
      ) {
        this.transferType = 2;
      }
    },
    submitted() {
      if (!this.transferTableData.every((item) => item && item.number > 0)) {
        this.$message.error('调拨数量不能为空');
        return;
      }
      this.doSubmit();
      //
    },
    doSubmit() {
      // 先判断是调拨还是采购
      if (this.defaultTransferOutType === 1) {
        // 调拨
        this.transferOrderSaves();
      } else {
        // 采购
        if(this.sendType == '采购入库'){
          this.purchaseOrderSave();
        }else if(this.sendType == '退货出库'){
          //
          this.returnOrderSave();
        }
      }
    },
    transferOrderSaves() {
      // 调拨
      inventoryTransferSave({
        receiptTime:
          this.receiptTime.getFullYear() + '-' + (this.receiptTime.getMonth() + 1) + '-' + this.receiptTime.getDate(), //得到YYYY-MM-DD
        transferOutRoomWarehouseId: this.transferOutStoreId[1],
        transferInRoomWarehouseId: this.transferInStoreId[1],
        transferOutType: this.transferOutType,
        transferInType: this.transferInType,
        transferReason: this.remarks,
        purchaseInWarehouseFormSkuListRequestList: this.transferTableData,
        transferOutRoomWarehouseName: this.transferOutRoomWarehouseName,
        transferInRoomWarehouseName: this.transferInRoomWarehouseName,
        transferType:this.transferType
      }).then((res) => {
        // console.log(res);
        this.$message.success('提交成功');
        this.transferTableData = [];
        this.remarks = '';
        this.transferOutStoreId = '';
        this.transferInStoreId = '';
        this.transferOutType = '';
        this.transferInType = '';
        this.showDrawer = false;
        this.productList = [];
        this.selectedCategoryId = '';
      });
    },
    purchaseOrderSave() {
      purchaseInWarehouseFormSave({
        receiptTime:
          this.receiptTime.getFullYear() + '-' + (this.receiptTime.getMonth() + 1) + '-' + this.receiptTime.getDate(), //得到YYYY-MM-DD
        merId: this.merId,
        merName: this.merName,
        warehouseId: this.warehouseId,
        warehouseName: this.warehouseName,
        remarks: this.remarks,
        purchaseInWarehouseFormSkuListRequestList: this.transferTableData,
      }).then((res) => {
        // console.log(res);
        this.$message.success('提交成功');
        this.transferTableData = [];
        this.remarks = '';
        this.merId = '';
        this.merName = '';
        this.warehouseId = '';
        this.warehouseName = '';
      });
      // 采购
    },
    returnOrderSave(){
      //退货
      addInOrOutWarehouseOrders({
        receiptTime:
          this.receiptTime.getFullYear() + '-' + (this.receiptTime.getMonth() + 1) + '-' + this.receiptTime.getDate(), //得到YYYY-MM-DD
        merId: this.merId,
        merName: this.merName,
        transferOutRoomWarehouseId: this.warehouseId,
        transferOutRoomWarehouseName: this.warehouseName,
        remarks: this.remarks,
        purchaseInWarehouseFormSkuListRequestList: this.transferTableData,
      }).then((res) => {
        // console.log(res);
        this.$message.success('提交成功');
        this.transferTableData = [];
        this.remarks = '';
        this.merId = '';
        this.merName = '';
        this.warehouseId = '';
        this.warehouseName = '';
      });
    },
    addProduct() {
      // 添加额外的前置检查
      if (this.isAddProductDisabled) {
        if (this.defaultTransferOutType === 1) {
          this.$message.warning('请先选择调出门仓和调入门仓');
        } else if (this.defaultTransferOutType === 0) {
          if (this.defaultTransferInType === 3) {
            this.$message.warning('请先选择供应商和入库仓库');
          } else {
            this.$message.warning('请先选择供应商和入库门仓');
          }
        }
        return;
      }

      productCategoryListApi().then((res) => {
        console.log(res);
        this.categoryTree = this.handleTree(res);
      });
      this.fetchProductList();
      this.showDrawer = true;
    },
    // 获取仓库门仓列表
    getStoreList() {
      // 类型(1仓库 2门仓)
      listStore({ type: 1, page: 1, limit: 999 }).then((res) => {
        // this.storeList = res.data;
        this.warehouseList = res.list.filter((item) => item.warehouseType == 1);
        console.log(res);
        this.storeList[0].children = res.list;
      });
      listStore({ type: 2, page: 1, limit: 999 }).then((resr) => {
        // this.storeList = res.data;
        this.storeRoomList = resr.list;
        console.log(resr);
        this.storeList[1].children = resr.list;
      });
      //组装成树状结构 门仓 仓库 联级选择器
      console.log(this.storeList);
    },
    getSupplierList() {
      merchantListApi({ page: 1, limit: 999 }).then((res) => {
        this.supplierList = res.list;
      });
    },
    handleTree(data) {
      // 将平铺的数组转为树结构，el-tree 需要 children 字段
      const idMap = {};
      const tree = [];
      data.forEach((item) => {
        // 适配 el-tree 的 label 字段
        item.label = item.name;
        item.children = [];
        idMap[item.id] = item;
      });
      data.forEach((item) => {
        if (item.pid && idMap[item.pid]) {
          idMap[item.pid].children.push(item);
        } else {
          tree.push(item);
        }
      });
      return tree;
    },
    async fetchProductList() {
      try {
        const queryType = this.defaultTransferOutType === 1 ? 'transfer' : 'purchase';
        const extraParams =
          this.defaultTransferOutType === 1
            ? {
                transferOutStoreId: this.transferOutStoreId[1],
                transferOutType: this.transferOutType,
                transferInStoreId: this.transferInStoreId[1],
                transferInType: this.transferInType,
              }
            :  this.sendType == '采购入库' ? {
                merId: this.merId,
                merName: this.merName,
              } : {
                merId: this.merId,
                merName: this.merName,
                warehouseId: this.warehouseId,
                warehouseName: this.warehouseName,
              };
        console.log(extraParams, 725,this.itemNumber,this.barCode);
        const params = buildProductQueryParams({
          categoryId: this.selectedCategoryId,
          limit: this.pageSize,
          page: this.page,
          productName: this.searchKeyword,
          itemNumber: this.itemNumber,
          barCode: this.barCode,
          queryType,
          extraParams,
        });

        const { list, total } = await fetchProducts({ ...params, queryType });
        this.productList = list;
        this.total = total;
      } catch (error) {
        console.error('获取商品列表失败:', error);
        this.$message.error('获取商品列表失败');
      }
    },
    handleSelectionChange(val) {
      this.selectedProducts = val;
    },
    handlePageChange(newPage) {
      this.page = newPage;
      this.fetchProductList();
    },
    handleBatchAdd() {
      // 检查选中的商品是否已经存在于列表中
      const newProducts = [];
      const duplicateProducts = [];
      
      this.selectedProducts.forEach(product => {
        const existingIndex = findExistingProduct(this.transferTableData, product);
        if (existingIndex >= 0) {
          duplicateProducts.push(product);
        } else {
          newProducts.push(product);
        }
      });
      
      if (newProducts.length === 0) {
        this.$message.warning('选中的商品已全部存在于列表中');
        return;
      }
      
      if (duplicateProducts.length > 0) {
        this.$message.warning(`${duplicateProducts.length}个商品已存在于列表中，已跳过`);
      }
      
      this.transferTableData.push(...newProducts);
      this.showDrawer = false;
      this.selectedProducts = [];
    },
    handleDrawerClose() {
      this.showDrawer = false;
      this.page = 1;
      this.pageSize = 10;
      this.selectedProducts = [];
    },
    handleCategoryClick(node) {
      this.selectedCategoryId = node.id;
      this.page = 1;
      this.fetchProductList();
    },
    handleRowAdd(index) {
      // 可根据业务需求实现行复制
      const row = { ...this.transferTableData[index] };
      this.transferTableData.splice(index + 1, 0, row);
    },
    handleRowRemove(index) {
      this.transferTableData.splice(index, 1);
    },
  },

  filters: {
    padIndex(val) {
      return (val + 1).toString().padStart(3, '0');
    },
  },
  computed: {
    transferTableDataWithAdd() {
      return [...this.transferTableData];
    },
    // 添加商品按钮是否禁用
    isAddProductDisabled() {
      if (this.defaultTransferOutType === 1) {
        // 调拨场景：需要选择调出门仓和调入门仓
        return !this.transferOutStoreId || !this.transferInStoreId;
      } else if (this.defaultTransferOutType === 0) {
        // 采购场景：需要选择供应商和仓库
        if (this.defaultTransferInType === 3) {
          // 采购入库到仓库
          return !this.merId || !this.warehouseId;
        } else if (this.defaultTransferInType === 1) {
          // 采购入库到门仓
          return !this.merId || !this.transferInStoreId;
        }
      }
      return true; // 默认禁用
    },
  },
};
</script>

<style scoped>
.transfer-add-container {
  background: #f5f6fa;
  min-height: 100vh;
  padding: 24px 32px;
}

.store-select-form {
  background: #fff;
  padding: 24px 24px 10px 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
  margin-bottom: 24px;
}

.drawer-content-flex {
  display: flex;
  height: 100%;
}

.category-tree-panel {
  width: 220px;
  margin-right: 24px;
  border: 1px solid #e4e7ed;
  background: #fafbfc;
  border-radius: 6px;
  padding: 16px 8px;
  max-height: 80vh;
  overflow-y: auto;
}

.product-list-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
}

.product-list-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.drawer-footer-btns {
  text-align: right;
  margin-top: 18px;
}

::v-deep .el-drawer__body {
  padding: 32px 32px 16px 32px;
}

.transfer-table-wrapper {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
  padding: 18px 24px 24px 24px;
  margin-bottom: 24px;
}

.add-row-cell {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 40px;
}
.add-product-btn {
  color: #409eff;
  border: 1px dashed #409eff;
  background: #f8fbff;
  font-weight: 500;
  border-radius: 4px;
  padding: 0 24px;
  transition: all 0.2s;
}
.add-product-btn:hover {
  background: #ecf5ff;
  border-color: #66b1ff;
  color: #337ecc;
}
</style>
